<template>
  <div class="wrapper-container">
    <div v-if="loading" class="loading">Loading components...</div>
    <div v-else-if="error" class="error">Error loading components: {{ error }}</div>
    <div 
      v-else
      class="component-wrapper"
      :class="{ 
        'selected': isSelected,
        'is-container': isContainer
      }"
      @click="selectComponent"
    >
      <!-- 组件类型标签 -->
      <div 
        class="component-type"
        :data-props="getPropsSummary"
      >
        {{ component }}
      </div>
      
      <!-- 组件内容 -->
      <div class="component-content">
        <component 
          :is="component" 
          v-bind="processedProps"
        >
          <!-- 为特定组件添加默认内容 -->
          <template v-if="needsDefaultContent">
            {{ defaultContent }}
          </template>
          
          <!-- 容器组件的插槽内容 -->
          <template v-if="isContainer">
            <div 
              class="container-slot"
              @drop="onDrop"
              @dragover.prevent
              @dragenter.prevent
            >
              <UniversalComponentWrapper
                v-for="(child, index) in children"
                :key="index"
                :component="child.component"
                :props="child.props"
                :children="child.children || []"
                @selected="$emit('childSelected', index)"
                @update:children="(newChildren) => updateNestedChildren(index, newChildren)"
                @childSelected="(childIdx) => $emit('childSelected', [index, childIdx].flat())"
              />
              <div v-if="!children.length" class="empty-container-hint">
                拖放组件到此处
              </div>
            </div>
          </template>
        </component>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, computed } from 'vue'
import * as ElementPlus from 'element-plus'

export default defineComponent({
  name: 'UniversalComponentWrapper',
  components: {
    ...ElementPlus
  },
  props: {
    component: {
      type: String,
      required: true
    },
    props: {
      type: Object,
      default: () => ({})
    },
    children: {
      type: Array,
      default: () => []
    }
  },
  emits: ['selected', 'update:children', 'childSelected'],
  setup(props, { emit }) {
    const loading = ref(false)
    const error = ref(null)
    const isSelected = ref(false)
    const children = ref(props.children || [])
    
    // 判断是否是容器组件
    const isContainer = computed(() => {
      const containerComponents = [
        'ElRow', 'ElCol', 'ElCard', 'ElContainer', 
        'ElHeader', 'ElAside', 'ElMain', 'ElFooter',
        'ElTabPane', 'ElCollapseItem', 'ElFormItem'
      ]
      return containerComponents.includes(props.component)
    })
    
    // 判断组件是否需要默认内容
    const needsDefaultContent = computed(() => {
      const componentsWithDefaultContent = [
        'ElLink', 'ElTag', 'ElRadioButton', 'ElCheckbox'
      ]
      return componentsWithDefaultContent.includes(props.component) && !isContainer.value
    })
    
    // 为组件提供默认内容
    const defaultContent = computed(() => {
      const contentMap = {
        'ElButton': '按钮',
        'ElLink': '链接',
        'ElTag': '标签',
        'ElRadioButton': '单选',
        'ElCheckbox': '复选框',
        'default': props.component.replace('El', '')
      }
      return contentMap[props.component] || contentMap.default
    })
    
    // 处理组件属性，添加默认样式
    const processedProps = computed(() => {
      const newProps = { ...props.props }
      
      // 为特定组件添加默认属性
      switch(props.component) {
        case 'ElButton':
          if (!newProps.type) newProps.type = 'primary'
          // 确保text属性是Boolean类型
          if (newProps.text && typeof newProps.text === 'string') {
            newProps.text = newProps.text === 'true'
          }
          break
        case 'ElInput':
          if (!newProps.placeholder) newProps.placeholder = '请输入内容'
          break
        case 'ElSelect':
          if (!newProps.placeholder) newProps.placeholder = '请选择'
          break
        case 'ElTable':
          newProps.style = { ...(newProps.style || {}), minHeight: '100px' }
          break
        case 'ElForm':
          newProps.style = { ...(newProps.style || {}), minHeight: '100px' }
          break
        case 'ElCard':
          if (!newProps.header) newProps.header = '卡片标题'
          newProps.style = { ...(newProps.style || {}), minHeight: '150px' }
          break
        case 'ElRow':
          if (!newProps.gutter) newProps.gutter = 20
          newProps.style = { 
            ...(newProps.style || {}), 
            minHeight: '100px', 
            backgroundColor: 'rgba(64, 158, 255, 0.05)',
            padding: '10px',
            marginBottom: '10px'
          }
          break
        case 'ElCol':
          if (!newProps.span) newProps.span = 12
          newProps.style = { 
            ...(newProps.style || {}), 
            minHeight: '80px', 
            backgroundColor: 'rgba(103, 194, 58, 0.05)',
            padding: '10px',
            border: '1px dashed rgba(103, 194, 58, 0.3)',
            // 确保列组件内容与包装器一致
            width: '100%',
            height: '100%',
            boxSizing: 'border-box'
          }
          break
      }
      
      return newProps
    })
    
    // 处理拖放事件
    const onDrop = (e) => {
      e.preventDefault()
      e.stopPropagation()
      try {
        const componentData = JSON.parse(e.dataTransfer.getData('application/json'))
        if (componentData && componentData.component) {
          // 转换组件名称格式 (el-button -> ElButton)
          const componentName = componentData.component
            .split('-')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join('')
          
          children.value.push({
            component: componentName,
            props: componentData.props || {},
            children: []
          })
          emit('update:children', children.value)
          console.log('组件已添加到容器:', componentName, children.value)
        }
      } catch (error) {
        console.error('拖放数据解析错误:', error)
      }
    }
    
    // 更新嵌套组件的子组件
    const updateNestedChildren = (childIndex, newChildren) => {
      if (children.value[childIndex]) {
        children.value[childIndex].children = newChildren
        emit('update:children', children.value)
      }
    }
    
    // 生成属性摘要
    const getPropsSummary = computed(() => {
      const props = processedProps.value
      if (!props || Object.keys(props).length === 0) return ''
      
      const summary = []
      
      // 基础属性
      if (props.type) summary.push(`type:${props.type}`)
      if (props.size) summary.push(`size:${props.size}`)
      if (props.disabled) summary.push('disabled')
      if (props.round) summary.push('round')
      if (props.plain) summary.push('plain')
      if (props.loading) summary.push('loading')
      
      // 文本相关
      if (props.placeholder) summary.push(`"${props.placeholder}"`)
      if (props.label) summary.push(`label:"${props.label}"`)
      
      // 样式属性
      if (props.style) {
        const styleKeys = Object.keys(props.style)
        if (styleKeys.includes('width')) summary.push(`w:${props.style.width}`)
        if (styleKeys.includes('height')) summary.push(`h:${props.style.height}`)
        if (styleKeys.includes('color')) summary.push(`color:${props.style.color}`)
        if (styleKeys.includes('backgroundColor')) summary.push(`bg:${props.style.backgroundColor}`)
      }
      
      // 特殊属性
      if (props.options) summary.push(`options:${props.options.length}`)
      if (props.data) summary.push(`data:${props.data.length}`)
      
      return summary.length > 0 ? 
        summary.slice(0, 5).join(' ') + (summary.length > 5 ? '...' : '') 
        : ''
    })

    // 处理子组件选择
    const onChildSelected = (childIndex) => {
      emit('childSelected', childIndex)
    }
    
    const selectComponent = () => {
      isSelected.value = true
      emit('selected')
    }

    return {
      getPropsSummary,
      loading,
      error,
      isSelected,
      children,
      selectComponent,
      needsDefaultContent,
      defaultContent,
      processedProps,
      isContainer,
      onDrop
    }
  }
})
</script>

<style scoped>
.wrapper-container {
  width: 100%;
  margin: 8px;
  position: relative;
}

.loading, .error {
  padding: 1rem;
  text-align: center;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.error {
  color: #f56c6c;
  border: 1px solid #fde2e2;
  background-color: #fef0f0;
}

.component-wrapper {
  border: 1px dashed #ccc;
  border-radius: 4px;
  padding: 12px;
  cursor: pointer;
  position: relative;
  background-color: rgba(245, 247, 250, 0.6);
  min-height: 40px;
  transition: all 0.3s;
}

.component-wrapper:hover {
  border-color: #409EFF;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.component-wrapper.selected {
  border: 2px solid #409eff;
  background-color: #f5f7fa;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.3);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.component-type {
  position: absolute;
  top: -10px;
  left: 8px;
  background-color: #f2f6fc;
  color: #606266;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid #dcdfe6;
  z-index: 1;
  display: flex;
  align-items: center;
  max-width: 280px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.component-type::before {
  content: '⚙️';
  margin-right: 4px;
  font-size: 10px;
}

.component-type::after {
  content: attr(data-props);
  margin-left: 6px;
  color: #909399;
  font-size: 11px;
  font-family: 'Courier New', monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 220px;
  display: inline-block;
  vertical-align: middle;
  background: rgba(0,0,0,0.03);
  padding: 0 4px;
  border-radius: 3px;
}

.component-wrapper.selected .component-type {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

.component-wrapper.selected .component-type::after {
  color: #e6f7ff;
  background: rgba(255,255,255,0.15);
}

.component-content {
  /* 基础布局 */
  position: relative !important;
  min-height: 24px;
  width: 100%;
  height: 100%;
  
  /* 强制定位上下文 */
  isolation: isolate;
  contain: layout;
  
  /* 调试边界 - 上线前可移除 */
  outline: 1px dashed rgba(255, 0, 0, 0.5);
  
  /* 绝对定位子元素处理 */
  > [style*="position: absolute"],
  > [style*="position:absolute"] {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
    margin: 0 !important;
    z-index: 1;
  }
  
  /* 非绝对定位子元素 */
  > *:not([style*="position: absolute"]):not([style*="position:absolute"]) {
    position: relative;
    width: 100%;
    height: 100%;
  }
  
  /* 溢出处理 */
  overflow: hidden;
}

/* 确保el-col内部元素正确布局 */
.component-content :deep(.el-col) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 80px;
  background-color: rgba(103, 194, 58, 0.05);
  padding: 10px;
  border: 1px dashed rgba(103, 194, 58, 0.3);
  box-sizing: border-box;
}

.component-content :deep(.el-col > *) {
  flex: 1;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 确保容器组件内部布局正确 */
.component-content :deep(.el-row) {
  width: 100%;
  height: 100%;
  margin: 0 !important;
}

/* 确保表单组件布局正确 */
.component-content :deep(.el-form-item) {
  margin-bottom: 0;
  width: 100%;
  height: 100%;
}

.component-content :deep(.el-form-item__content) {
  display: flex;
  flex-direction: column;
  flex: 1;
}

/* 特定组件样式调整 */
.component-content :deep(.el-input),
.component-content :deep(.el-select),
.component-content :deep(.el-date-picker) {
  width: 100%;
}

.component-content :deep(.el-form-item) {
  margin-bottom: 0;
}

/* 容器组件样式 */
.component-wrapper.is-container {
  background-color: rgba(245, 247, 250, 0.8);
  border: 2px dashed #c0c4cc;
  padding: 15px;
}

.component-wrapper.is-container:hover {
  border-color: #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

.component-wrapper.is-container.selected {
  border: 2px solid #409EFF;
  background-color: rgba(64, 158, 255, 0.1);
}

/* 容器插槽样式 */
.container-slot {
  min-height: 60px;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.container-slot:hover {
  background-color: rgba(64, 158, 255, 0.05);
}

/* 空容器提示 */
.empty-container-hint {
  color: #909399;
  font-size: 12px;
  text-align: center;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: rgba(220, 223, 230, 0.2);
}

/* 嵌套组件间距 */
.container-slot > .wrapper-container {
  margin: 8px 0;
}
</style>